HackerRank Matrix Layer Rotation
https://www.hackerrank.com/challenges/matrix-rotation-algo/problem
解答
code: python
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'matrixRotation' function below.
#
# The function accepts following parameters:
# 1. 2D_INTEGER_ARRAY matrix
# 2. INTEGER r
#
def matrixRotation(matrix, r):
# Write your code here
# temporary matrix
mat = []
k = min(m,n) // 2 # compute no. of layers
# to get elements from the layer
for i in range(k):
temp = []
# a11 - a14
for j in range(i, n-1-i): # -i: to reduce layer
temp.append(matrixij)
# a15 - a35
for j in range(i, m-1-i):
temp.append(matrixjn-1-i)
# a45 - a42
for j in range(n-1-i, i, -1):
temp.append(matrixm-1-ij)
# a41 -a21
for j in range(m-1-i, i, -1):
temp.append(matrixji)
mat.append(temp)
# rotate elements and place it in original matrix
for i in range(k):
row = mati
# find index after rotation
idx = r % len(row)
def inc():
return (idx + 1) % len(row)
for j in range(i, n-1-i): # -i: to reduce layer
matrixij = rowidx
idx = inc()
for j in range(i, m-1-i):
matrixjn-1-i = rowidx
idx = inc()
for j in range(n-1-i, i, -1):
matrixm-1-ij = rowidx
idx = inc()
for j in range(m-1-i, i, -1):
matrixji = rowidx
idx = inc()
# print the matrix
for row in matrix:
print(*row)
if __name__ == '__main__':
first_multiple_input = input().rstrip().split()
m = int(first_multiple_input0)
n = int(first_multiple_input1)
r = int(first_multiple_input2)
matrix = []
for _ in range(m):
matrix.append(list(map(int, input().rstrip().split())))
matrixRotation(matrix, r)
メモ
https://www.youtube.com/watch?v=acGcfh4JJiI